<template>
  <div class="confirm-order">
    <minor-header title="确认订单"></minor-header>
    <div class="wrap">
      <h2>收货地址</h2>
      <div id="address" class="f-fs-fs">
        <div
          class="box"
          v-for="(item, ind) in address"
          :key="ind"
          :class="ind == currAdsInd ? 'active' : ''"
          @click="changeAdsInd(ind)"
        >
          <div id="head" class="f-sb-c">
            <b>{{ item.user_name }}</b>
            <b>{{ item.user_tel }}</b>
          </div>
          <div id="body">
            {{ item.province + item.city + item.county + item.detail }}
          </div>
          <div id="foot" class="flex-start-center">
            <el-button size="mini" type="danger" @click="goUpdateAddress()"
              >修改</el-button
            >
            <el-button size="mini" type="danger" @click="delAddress(item.id)"
              >删除</el-button
            >
          </div>
        </div>
        <el-tooltip
          id="add"
          content="添加收货地址"
          class="f-c-c"
          placement="top"
        >
          <i class="el-icon-plus" @click="goAddAddress"></i>
        </el-tooltip>
      </div>
      <h2>订单信息</h2>
      <line-deal :goods="goods"></line-deal>
      <div id="confirm" class="f-c-c">
        <table id="left">
          <tr>
            <td>总价</td>
            <td>￥3306.00</td>
          </tr>
          <tr>
            <td>运费</td>
            <td>+￥0</td>
          </tr>
          <tr>
            <td>优惠券</td>
            <td>-￥15</td>
          </tr>
          <tr>
            <td>积分</td>
            <td>-￥10</td>
          </tr>
          <tr>
            <td>结算金额</td>
            <td>-￥3306.00</td>
          </tr>
        </table>
        <div id="middle">
          <div><b>实付款：</b><strong>￥3306.00</strong></div>
          <div><b>寄送至：</b>XXXX详细地址信息</div>
          <div><b>收货人：</b><span>XXX</span><span>111111111电话</span></div>
        </div>
        <div id="right">
          <el-button type="primary">提交订单</el-button>
        </div>
      </div>
    </div>
    <el-dialog :title="operateTitle" :visible.sync="isShowDialog">
      <el-form :model="form" :rules="formRules" ref="adsForm">
        <el-form-item
          label="姓名"
          label-width="80px"
          :prop="operateType + '.name'"
        >
          <el-input
            v-model="form[operateType].name"
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="电话"
          label-width="80px"
          :prop="operateType + '.tel'"
        >
          <el-input
            v-model="form[operateType].tel"
            placeholder="请输入电话"
          ></el-input>
        </el-form-item>
        <div class="f-sb-c">
          <el-form-item
            label="省"
            label-width="40px"
            style="margin-left: 40px"
            :prop="operateType + '.provinceId'"
          >
            <el-select
              v-model="form[operateType].provinceId"
              placeholder="请选择所在省"
              style="width: 140px"
              @change="changeProvince"
            >
              <el-option label="--请选择--" :value="null"></el-option>
              <el-option
                :label="item.province"
                :value="item.province_id"
                v-for="(item, ind) in province"
                :key="ind"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="市"
            label-width="40px"
            :prop="operateType + '.cityId'"
          >
            <el-select
              v-model="form[operateType].cityId"
              placeholder="请选择所在市"
              style="width: 140px"
              @change="changeCity"
            >
              <el-option label="--请选择--" :value="null"></el-option>
              <el-option
                :label="item.city"
                :value="item.city_id"
                v-for="(item, ind) in city"
                :key="ind"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="县"
            label-width="40px"
            :prop="operateType + '.countyId'"
          >
            <el-select
              v-model="form[operateType].countyId"
              placeholder="请选择所在县"
              style="width: 140px"
            >
              <el-option label="--请选择--" :value="null"></el-option>
              <el-option
                :label="item.county"
                :value="item.county_id"
                v-for="(item, ind) in county"
                :key="ind"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item
          label="详细地址"
          label-width="80px"
          :prop="operateType + '.detail'"
        >
          <el-input
            type="textarea"
            rows="4"
            v-model="form[operateType].detail"
            placeholder="请输入详细地址"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onClose">关闭</el-button>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// import reg from "@/public/js/regexp.js";
import MinorHeader from "../components/section/MinorHeader.vue";
import LineDeal from "../components/side/LineDeal.vue";
// import { twoObjsIsEqual } from "../../public/js/utility.js";
let vm = {};
export default {
  name: "ConfirmOrder",
  components: {
    MinorHeader,
    LineDeal,
  },
  data() {
    let vdtTel = this.validator("电话号码", reg.tel);
    let vdtName = this.validator("姓名", reg.name);
    return {
      reg: null,
      textarea: "",
      currAdsInd: 0,
      address: [], //收货地址
      userInfo: this.$store.state.userInfo,

      province: [],
      city: [],
      county: [],
      operateType: "add", //add新增收货地址、update修改收货地址
      isShowDialog: false,
      form: {
        add: {
          name: "范力川",
          tel: "18483221518",
          provinceId: 0, //null
          cityId: 0, //null
          countyId: 0, //null
          detail: "随便写的详细地址内容",
          userId: this.$store.state.userInfo.id,
        },
        update: {
          name: "",
          tel: "",
          provinceId: null,
          cityId: null,
          countyId: null,
          detail: "",
          id: 0, //地址id
        },
      },
      formRules: {
        "add.tel": [{ required: true, validator: vdtTel, trigger: "blur" }],
        "add.name": [{ required: true, validator: vdtName, trigger: "blur" }],
        "add.provinceId": [
          { required: true, message: "请选择省", trigger: "change" },
        ],
        "add.cityId": [
          { required: true, message: "请选择市", trigger: "change" },
        ],
        "add.countyId": [
          { required: true, message: "请选择县", trigger: "change" },
        ],
        "add.detail": [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        "update.tel": [{ required: true, validator: vdtTel, trigger: "blur" }],
        "update.name": [
          { required: true, validator: vdtName, trigger: "blur" },
        ],
        "update.provinceId": [
          { required: true, message: "请选择省", trigger: "change" },
        ],
        "update.cityId": [
          { required: true, message: "请选择市", trigger: "change" },
        ],
        "update.countyId": [
          { required: true, message: "请选择县", trigger: "change" },
        ],
        "update.detail": [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
      },
      goods: [],
    };
  },
  watch: {},
  computed: {
    operateTitle() {
      let title = "";
      switch (this.operateType) {
        case "add":
          title = "新增收货地址";
          break;
        case "update":
          title = "修改收货地址";
          break;
        default:
          break;
      }
      return title;
    },
  },
  methods: {
    initData() {
      this.getAddress();
      this.getProvince();
    },
    initUpdateForm() {
      let { operateType, address, currAdsInd, form } = this;
      let updateForm = form[operateType];
      let currAds = address[currAdsInd];
      updateForm.id = currAds.id;
      updateForm.name = currAds.user_name;
      updateForm.tel = currAds.user_tel;
      updateForm.provinceId = currAds.province_id;
      updateForm.cityId = currAds.city_id;
      updateForm.countyId = currAds.county_id;
      updateForm.detail = currAds.detail;
    },
    validator(vdtName, regexp) {
      return (rule, val, cb) => {
        if (val.toString().length == 0) {
          cb(new Error("请输入" + vdtName));
        } else if (!new RegExp(regexp).test(val)) {
          cb(new Error("请输入正确的" + vdtName));
        } else {
          cb();
        }
      };
    },
    openDialog() {
      if (this.operateType == "update") {
        this.city.length == 0 && this.getCity();
        this.county.length == 0 && this.getCounty();
      }
      this.isShowDialog = true;
    },
    closeDialog() {
      this.isShowDialog = false;
    },
    getProvince() {
      this.$axios
        .get("/data/getProvince")
        .then((res) => {
          console.log(res.data.data);
          this.province = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getCity() {
      let { provinceId } = this.form[this.operateType];
      this.$axios
        .get("/data/getCity?provinceId=" + provinceId)
        .then((res) => {
          console.log(res.data.data);
          this.city = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getCounty() {
      let { provinceId, cityId } = this.form[this.operateType];
      this.$axios
        .get(`/data/getCounty?provinceId=${provinceId}&cityId=${cityId}`)
        .then((res) => {
          console.log(res.data.data);
          this.county = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getAddress() {
      let { userInfo } = this;
      this.$axios
        .get("/data/getAddressByUserId", {
          params: { userId: userInfo.id },
        })
        .then((res) => {
          console.log(res.data.data);
          this.address = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    changeProvince(val) {
      if (val !== null) {
        this.getCity();
        this.form[this.operateType].cityId = null;
        this.form[this.operateType].countyId = null;
        this.county.length > 0 && (this.county = []);
      }
    },
    changeCity(val) {
      if (val !== null) {
        this.getCounty();
        this.form[this.operateType].countyId = null;
      }
    },
    changeAdsInd(ind) {
      this.currAdsInd = ind;
    },
    goAddAddress() {
      this.operateType = "add";
      this.openDialog();
    },
    addAddress() {
      this.$axios
        .get(`/data/addAddress`, {
          params: this.form.add,
        })
        .then((res) => {
          let { code, msg } = res.data;
          console.log(res.data);
          if (code == 1) {
            this.$message.success(msg);
            this.getAddress();
            this.closeDialog();
          } else {
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    updateAddress() {
      this.$axios
        .get(`/data/updateAddress`, {
          params: this.form.update,
        })
        .then((res) => {
          let { code, msg } = res.data;
          console.log(res.data);
          if (code == 1) {
            this.$message.success(msg);
            this.getAddress();
            this.closeDialog();
          } else {
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    delAddress(adsId) {
      this.$confirm("此操作将删除此收货地址, 是否继续?", "消息提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .get("/data/delAddress", { params: { id: adsId } })
            .then((res) => {
              let { code, msg } = res.data;
              if (code == 1) {
                this.$message.success(msg);
                this.getAddress();
              } else {
                this.$message.error(msg);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message.info("已取消删除！");
        });
    },
    goUpdateAddress() {
      this.operateType = "update";
      this.initUpdateForm();
      this.openDialog();
    },
    onClose() {
      this.closeDialog();
    },
    onSubmit() {
      let { operateType } = this;
      this.$refs.adsForm.validate((isValid) => {
        if (isValid) {
          this[operateType + "Address"]();
        } else {
          this.$message.error("请按提示填写信息！");
        }
      });
    },
  },
  beforeCreate() {
    vm = this;
  },
  created(){
    // this.goods=JSON.parse(sessionStorage.getItem("goods"));
    // console.log(this.goods)
  },
  mounted() {
    this.initData();
    console.log(this.form);
  },
};
</script>
<style lang="scss" scoped>
.wrap {
  margin-bottom: 50px;
}
#address {
  flex-wrap: wrap;
}
#add {
  cursor: pointer;
  color: $border-color-extra-light;
  width: 133px;
  height: 133px;
  border-radius: 10px;
  border: 4px dashed $border-color-extra-light;
  font-size: 60px;
}
.box {
  cursor: pointer;
  width: 255px;
  padding: 9px 10px;
  border-radius: 10px;
  border: 4px dashed $border-color-base;
  margin-bottom: 20px;
  &:not(:nth-child(4n)) {
    margin-right: 20px;
  }
}
.active,
.box:hover,
#add:hover {
  border: 4px dashed $theme-color;
}
h2 {
  color: #ffffff;
  font-size: 16px;
  line-height: 40px;
  padding: 0 10px;
  border-radius: $border-radius-base;
  margin: 20px 0;
  background: $theme-color;
}
#body {
  padding: 5px 0;
  margin: 5px 0;
  line-height: 22px;
  height: 44px;
  @include text-ellipsis(2);
  border-top: 1px solid $border-color-base;
  border-bottom: 1px solid $border-color-base;
}


#confirm {
  background: $background-color-base;
  border: 1px solid $theme-color;
  border-radius: $border-radius-base;
  padding: 15px 0;
  #left {
    width: auto;
  }
  #middle {
    color: $color-text-secondary;
    font-size: 14px;
    padding: 0 50px;
    margin: 0 50px;
    line-height: 36px;
    border-left: 1px dashed $border-color-extra-light;
    border-right: 1px dashed $border-color-extra-light;
    b {
      color: #000000;
    }
    strong {
      color: $rmb-color;
      font-size: 30px;
    }
    span:not(:last-child) {
      margin-right: 10px;
    }
  }
}

table {
  color: $color-text-secondary;
  width: 100%;
  font-size: 14px;
  line-height: 22px;
  border-collapse: collapse;
  td {
    vertical-align: top;
    &:first-child {
      text-align: right;
      width: 80px;
      padding-right: 10px;
    }
    &:last-child {
      padding-left: 10px;
    }
  }
}
</style>